﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace YDT.Projects.WebSite.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class SeckillProductController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<SeckillProductController> _logger;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IMemoryCache _memoryCache;// 本地缓存
        public SeckillProductController(ILogger<SeckillProductController> logger, 
            IHttpClientFactory httpClientFactory,
             IMemoryCache memoryCache)
        {
            _logger = logger;
            _httpClientFactory = httpClientFactory;
            _memoryCache = memoryCache;
        }
      

        /// <summary>
        /// 查询秒杀商品
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<string> Get()
        {
            System.Net.Http.HttpClient httpClient = _httpClientFactory.CreateClient("CacheClient");

            //var handler = new HttpClientHandler
            //{
            //    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
            //};
            //new System.Net.Http.HttpClient(handler);

            // 1、相当于直接查询(第三方服务)
            //var result = httpClient.GetAsync("http://localhost:5084/Seckills").Result;
            //本地缓存
            //HttpResponseMessage httpResponseMessage = _memoryCache.Get<HttpResponseMessage>("http://localhost:5084/Seckills");

            //if (httpResponseMessage == null) {
            //    //从远程查找
            //    httpResponseMessage = await httpClient.GetAsync("http://localhost:5084/Seckills");

            //    //存储到缓存中
            //    _memoryCache.Set<HttpResponseMessage>("http://localhost:5084/Seckills", httpResponseMessage);
            //}

            var httpResponseMessage = await httpClient.GetAsync("http://localhost:5084/Seckills");

            // 2、数据库
            // efcore + 数据库
            return await httpResponseMessage.Content.ReadAsStringAsync();

        }

        /// <summary>
        /// 查询秒杀商品列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetList")]
        public string GetList()
        {
            System.Net.Http.HttpClient httpClient = _httpClientFactory.CreateClient("CacheClient");

            // 1、相当于直接查询
            var result = httpClient.GetAsync("http://localhost:5084/GetList").Result;

            return result.Content.ReadAsStringAsync().Result;

        }
    }
}
